package handler

import (
	"encoding/json"
	"fun-park-mgr/cache"
	"fun-park-mgr/moder"
	"time"

	"github.com/gin-gonic/gin"
)

func Add(c *gin.Context) {

	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"mas":  "数据不能为空",
			"code": 500,
		})
		return
	}

	article := moder.Article{
		Username: username,
		Password: password,
	}

	err := moder.DB.Create(&article).Error

	if err != nil {
		c.JSON(200, gin.H{
			"mas":  "发布失败",
			"code": 500,
		})
		return
	}

	c.JSON(200, gin.H{
		"mas":  "发布成功",
		"code": 200,
		"data": article,
	})
	return

}

func Del(c *gin.Context) {

	id := c.PostForm("id")
	var user moder.Article

	moder.DB.Where("id=?", id).Debug().Delete(&user)

	c.JSON(200, gin.H{
		"mas":  "删除成功",
		"code": 200,
	})
	return

}

func List(c *gin.Context) {
	var article []moder.Article

	redis_list_ley := "list_art"
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_ley).Result()
	if result == "" {
		moder.DB.Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_list_ley, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &article)
	}

	c.JSON(200, gin.H{
		"mas":  "获取数据成功",
		"code": 200,
	})
	return

}
